﻿using System;
using System.Diagnostics;
using System.IO;

using Microsoft.Deployment.WindowsInstaller;

namespace Microsoft.Coding4Fun.TweetCraft.Setup
{
    public class CustomActions
    {
        [CustomAction]
        public static ActionResult KillProcessByName(Session session)
        {
            session.Log("Begin KillProcessByName");

            try
            {
                string processNameToKill = session["PROCESSNAMETOKILL"];

                if (String.IsNullOrEmpty(processNameToKill))
                {
                    session.Log("PROCESSNAMETOKILL does not contain a valid process name.");
                    return ActionResult.NotExecuted;
                }

                Process[] processes = Process.GetProcessesByName(processNameToKill);

                session.Log("Found {0} process(es) with name '{1}'.", processes.Length, processNameToKill);

                if (processes.Length > 0)
                {
                    foreach (var process in processes)
                        process.Kill();

                    session.Log("All process(es) killed.");
                }

                return ActionResult.Success;
            }
            finally
            {
                session.Log("End KillProcessByName");
            }
        }

        [CustomAction]
        public static ActionResult DeleteTweetCraftAddOn(Session session)
        {
            session.Log("Begin DeleteTweetCraftAddOn");

            try
            {
                string wowInstallPath = session["WOWINSTALLPATH"];

                if (String.IsNullOrEmpty(wowInstallPath))
                {
                    session.Log("World of Warcraft installation not detected.");
                    return ActionResult.NotExecuted;
                }

                string tweetCraftPath = Path.Combine(wowInstallPath, @"Interface\AddOns\TweetCraft");

                if (!Directory.Exists(tweetCraftPath))
                {
                    session.Log("TweetCraft add-on not detected.");
                    return ActionResult.NotExecuted;
                }

                // Delete the folder
                Directory.Delete(tweetCraftPath, true);
                session.Log("Deleted TweetCraft add-on recursively.", wowInstallPath);

                return ActionResult.Success;
            }
            finally
            {
                session.Log("End DeleteTweetCraftAddOn");
            }

        }
    }
}
